<?php
require_once(dirname(__FILE__) . "/class.Property.php");
/*
*
* This is a class which is the collection of database related methods
* @version 0.01

* @Date 17 Nov, 2011
* @modified 18 Nov, 2011 
*
**/
class DataAccess extends Property{
	
	protected $dbCon;		/* member variable that holds the database connectivity resource */
	protected $dbCon1;
	protected $rsResource;	/* member variable that holds the result/resource */
	protected $sql;
	/*
	* This is the constructor of the class Database
	* which initializes the database connectivity
	
	* @Date 17 Nov, 2011
	* @modified 18 Nov, 2011 
	*/
	public function __construct(){
		$this->dbCon = mssql_connect(HOST, DBUSER, DBPASSWD);
		if(!$this->dbCon)
			die('Could not connect to the server.Check in config.php');
		if(!mssql_select_db(DBNAME,$this->dbCon))
			die('Cannot select the database.');
	}
	
	public function getServerConnection($serviceId) {
		if($serviceId == 1) {
			$this->dbCon1 = mssql_connect(UTILITY_PREPAID_HOST,UTILITY_PREPAID_USER,UTILITY_PREPAID_PASS);
			if(!$this->dbCon1)
				die('Could not connect to the prepaid recharge card server.Check in config.php');
			if(!mssql_select_db(UTILITY_PREPAID_NAME,$this->dbCon1))
				die('Could not select prepaid recharge card database.');
			return $dbCon1;
		}
		else {
			return "No other server assigned.";	
		}
	}

	/*
	* This method is used to execute the query
	
	* @Date 17 Nov, 2011
	* @modified 18 Nov, 2011 
	* @param : $sql
	*/
	public function dbQuery($sql = ""){
		if(!$sql || $sql == ""){
			die('Empty SQL statement found!');
		}
		
		$this->rsResource = mssql_query($sql,$this->dbCon);
		if(!$this->rsResource){
			echo '<pre style="color:#FF000;">';
			echo $$sql;
			echo '</pre>';
			echo '<strong>system generated error:</strong><br>';
			die("error in connection");
			return false;
		}
		else{
			$this->sql = $sql;
			return true;
		}
	}
	/*
	* This method is used to execute the query and return the resource
	
	* @Date 17 Nov, 2011
	* @modified 18 Nov, 2011 
	* @param : $sql
	* @return : resource / result
	*/
	public function dbQueryReturn($sql = ""){
		if(!$sql || $sql == ""){
			die('Empty SQL statement found!');
		}
		$this->rsResource = mssql_query($sql,$this->dbCon);
		if($this->rsResource){
			$this->sql = $sql;
			return $this->rsResource;
		}
		else{
			return false;
		}
	}
	/*
	* This method is used to get the current sql;
	
	* @Date 17 Nov, 2011
	* @modified 18 Nov, 2011 
	* @return : integer
	*/
	public function showSql($dieme=false){
		if(is_resource($this->rsResource) && $this->sql){
			$this->showpre($this->sql,'SQL');
		}
		if($dieme) die('--die--');
	}
	/*
	* This method is used to get the current sql;
	
	* @Date 17 Nov, 2011
	* @modified 18 Nov, 2011 
	* @return : integer
	*/
	public function getSQL(){
		if(is_resource($this->rsResource) && $this->sql){
			return $this->sql;
		}
	}
	/*
	* This method is used to get the total records of a result
	
	* @Date : 10 Aug, 2007
	* @modified :  10 Aug, 2007 
	* @return : integer
	*/
	public function totalRecords(){
		if(is_resource($this->rsResource)){
			return mssql_num_rows($this->rsResource);
		}
	}
	/*
	* This method is used to fetch the result/resource row as associative array
	
	* @Date : 10 Aug, 2007
	* @modified :  10 Aug, 2007 
	* @param : $retType = return array type (1=ASSOC / 2 = NUM / 3 = OBJECT)
	* @param : $dbResource = query resource/result
	* @return : Array
	*/
	public function dbFetchArray($retType = 1){
		if(is_resource($dbResource)){
			if($retType == 1)
				return mssql_fetch_array($dbResource, MYSQL_ASSOC);
			else if($retType == 2)
				return mssql_fetch_assoc($dbResource);
			else if($retType == 3)
				return mssql_fetch_object($dbResource);
		}
		else if(is_resource($this->rsResource)){
			if($retType == 1)
				return mssql_fetch_array($this->rsResource, MYSQL_ASSOC);
			else if($retType == 2)
				return mssql_fetch_assoc($this->rsResource);
			else if($retType == 3)
				return mssql_fetch_object($this->rsResource);
		}
		else{
			die('Invalid resource!');
		}
	}
	//
	public function dbFetchAll()
	{
		$numFields = mssql_num_fields($this->rsResource);
		$y = 0;
		while($row = mssql_fetch_array($this->rsResource)) {
			$x = 0;
			while($x < $numFields) {
				$fieldName = mssql_field_name($this->rsResource, $x);
				$array[$y][$fieldName] = $row["$fieldName"];
				$x++;
			}
			$y++;
			$x = 0;
		}		
		return $array;
	}	
	//
	/*
	* This method is used to free the database result/resource
	
	* @Date : 10 Aug, 2007
	* @modified :  10 Aug, 2007 
	* @return : bool
	*/
	public function dbFree($dbResource){
		if(is_resource($dbResource)){
			mssql_free_result($dbResource);
		}
		else if(is_resource($this->rsResource)){
			mssql_free_result($this->rsResource);
		}
	}
	
	/*
	* This method is used to get the new code/id for the table.
	
	* @Date : 13 Dec, 2007
	* @modified :  13 Dec, 2007 
	* @return : bool
	*/
	public function genCode($table, $field){
		$Sql = "SELECT 
					MAX(" . $field . ") AS MaxValue
				FROM 
					" . $table . "
				WHERE
					1=1";
		$this->dbQuery($Sql);
		$rows = $this->dbFetchArray(1);
		if($rows['MaxValue'] != NULL && $rows['MaxValue'] != "")
			return $rows['MaxValue'];
		else
			return 1;
	}
/*
	* This method is used to run the stored procedures  for the table.
	
	* @Date : 13 Dec, 2007
	* @modified :  13 Dec, 2007 
	* @return : bool
	*/

 public function testProcedure($procname){
 	$arr=$this->PropertyDump();
	$status=0;
	$sp=mssql_init($procname) or die("error"); 
	foreach($arr as $key=>$val){
		mssql_bind($sp,'@'.$key,$val,SQLVARCHAR,FALSE);
		if($key=='offset')
			$status=1;
	}
	if($status==0){
		$offset='';
		$limit='';
		mssql_bind($sp,'@offset',$offset,SQLVARCHAR,FALSE);
		mssql_bind($sp,'@limit',$limit,SQLVARCHAR,FALSE);
	
	}
	
	$this->rsResource= mssql_execute($sp);
	if($this->rsResource)	
		return $this->rsResource;
 }
 
  
 public function executeProcedure($procname){
 		$arr=$this->PropertyDump();
		$oarr=array();
		foreach($arr as $key=>$val){
			$narr[$key]="'".$val."'";
		 if($key=='offset')
			 $status=1;	
		}
		if($status==0){
			$oarr['offset']="'".$offset."'";
			$oarr['limit']="'".$limit."'";
		}
		$narr=array_merge($oarr,$narr);
		$sql="exec ".$procname. implode(",",$narr);  
		//$this->showpre($sql);
		
 		$this->dbQuery($sql);
		//die();
	}
	
public function printProcedure($procname){
 		$arr=$this->PropertyDump();
		$oarr=array();
		foreach($arr as $key=>$val){
			$narr[$key]="'".$val."'";
		 if($key=='offset')
			 $status=1;	
		}
		if($status==0){
			$oarr['offset']="'".$offset."'";
			$oarr['limit']="'".$limit."'";
		}
		$narr=array_merge($oarr,$narr);
		
		$this->showpre($sp="exec ".$procname. implode(",",$narr),$procname);
		
	}	

	public function exportProcedure($procname){
 		$arr=$this->PropertyDump();
		foreach($arr as $key=>$val){
			$narr[$key]="'".$val."'";
		}
		$sql="exec ".$procname. implode(",",$narr);  
		return $sql;
	}
	//
	public function showpre($str,$variable='')
	{
		
		echo '<pre style="
			border:1px solid red; line-height:15px;font-size:12px;background-color:#eee;margin:3px;height:auto; margin-left:3%; 
			overflow:hidden; width:96%;padding:5px; color:#000; text-align:left;
			white-space: pre-wrap;
			white-space: -moz-pre-wrap !important;
			word-wrap: break-word;
			white-space: -o-pre-wrap;
			white-space: -pre-wrap;		
			">';
		if($variable!='')
		{
			echo '<p  style="border-bottom:1px solid red; color:#f00;font-weight:bold;padding:2px; margin:0px; text-align:left;">'.$variable.'</p>';
		}
		echo '<code>';
		print_r($str);
		echo '</code>';			
		echo '</pre>';
	}
	//

public function paginate($procname,$params){
 		$offset=OFFSET;
		$arr=$this->PropertyDump();
		foreach($arr as $key=>$val){
			if($key=='offset')
			   $val='';
			if($key=='limit')
			   $val='';   
		$new_arr[$key]="'".$val."'";
		} 	 
		$sql="exec ".$procname. implode(",",$new_arr); 
		$this->dbQuery($sql);
		$cnt=$this->totalRecords();
		if($cnt >= $offset){
		?>
			<div id="pagination">
				<?php
					if($_GET["limit"]>1){?>
				<span class="prev">
    				<a href="<?php echo SITE_URL.$_GET["page_id_f1"].$params?>&limit=<?php echo $_GET["limit"]-OFFSET?>&offset=<?php echo $_GET["limit"]-1?>">&laquo; Previous</a>
				</span>
				<?php }?>
		<?php
		$count=1;
		for($i=1;$i<=$cnt;$i=$i+$offset){
			
			if($cnt>$i+($offset-1))
				$off= $i+($offset-1);
			else
				$off=$cnt;
			
		if($_GET["limit"]!=$i){	
		?>
        <a href="<?php echo SITE_URL.$_GET["page_id_f1"].$params?>&limit=<?php echo $i?>&offset=<?php echo $off?>"><?php echo $count?></a> 
        <?php } else {?> 
				<span class="current_page"><?php echo $count;?></span>
		<?php }?> 
		<?php $count++;}?> 
 			<?php 
				if($_GET["offset"] <$off){?>
			<span class="next"><a href="<?php echo SITE_URL.$_GET["page_id_f1"].$params?>&limit=<?php echo $_GET["limit"]+OFFSET?>&offset=<?php echo $_GET["offset"]+OFFSET?>">Next &raquo;</a></span>
			<?php }?>
		</div>
	<?php
	}
	}


}
?>